package sf.database.template.enjoy.ext;

import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.io.CharWriter;
import com.jfinal.template.io.FastStringWriter;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import sf.tools.StringUtils;

/**
 * where指令
 */
public class WhereDirective extends Directive {
    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        CharWriter charWriter = new CharWriter(64);
        FastStringWriter fsw = new FastStringWriter();
        charWriter.init(fsw);
        try {
            stat.exec(env, scope, charWriter);
        } finally {
            charWriter.close();
        }
        String content = fsw.toString();
        if (StringUtils.isNotBlank(content)) {
//            content = SqlHelp.compressSql(content);
            content = content.trim();
            if (StringUtils.startsWithIgnoreCase(content, "and")) {
                content = content.substring(content.indexOf("and") + 3);
            } else if (StringUtils.startsWithIgnoreCase(content, "or")) {
                content = content.substring(content.indexOf("or") + 2);
            }
            content = " where " + content;
        }
        write(writer, content);
    }

    @Override
    public boolean hasEnd() {
        return true;
    }
}
